#!/bin/bash

# =====================
# 配置参数（可根据需要修改）
# =====================
GO_VERSION="1.22.3"
GO_URL_BASE="https://dl.google.com/go"
ARCH=$(uname -m)
PROFILE="/etc/profile.d/go.sh"

# 你要安装的依赖列表
DEPENDENCIES=(
    github.com/gin-gonic/gin@latest
    github.com/shirou/gopsutil/v3@latest
)

# 项目路径和构建设置
PROJECT_DIR="/opt/monitor-server"       # 你的 Go 项目目录
BINARY_NAME="monitor-server"            # 编译后的二进制名称
BINARY_PATH="/usr/local/bin/$BINARY_NAME" # 二进制存放路径
SERVICE_NAME="monitor-server"           # systemd 服务名
SERVICE_USER="${SUDO_USER:-$USER}"      # 默认使用当前用户

# 根据架构选择对应的压缩包
if [[ "$ARCH" == "x86_64" ]]; then
    GO_TAR="go${GO_VERSION}.linux-amd64.tar.gz"
elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
    GO_TAR="go${GO_VERSION}.linux-arm64.tar.gz"
else
    echo "不支持的架构: $ARCH"
    exit 1
fi

GO_DOWNLOAD_URL="${GO_URL_BASE}/${GO_TAR}"

# =====================
# 下载并解压 Go
# =====================
echo "正在下载 Go ${GO_VERSION} (${ARCH})..."
cd /tmp
curl -O "${GO_DOWNLOAD_URL}"
if [ $? -ne 0 ]; then
    echo "下载失败，请检查网络连接或版本是否存在。"
    exit 1
fi

echo "解压文件到 /usr/local..."
sudo tar -C /usr/local -xzf "${GO_TAR}"
rm -f "${GO_TAR}"

# =====================
# 配置环境变量
# =====================
echo "配置环境变量..."

echo "export GOROOT=/usr/local/go" | sudo tee "$PROFILE" > /dev/null
echo "export PATH=\$PATH:\$GOROOT/bin" | sudo tee -a "$PROFILE" > /dev/null
echo "export GOPROXY=https://goproxy.io,direct" | sudo tee -a "$PROFILE" > /dev/null
echo "export GOSUMDB=sum.golang.org" | sudo tee -a "$PROFILE" > /dev/null

source "$PROFILE"

# =====================
# 验证 Go 是否安装成功
# =====================
echo "验证安装..."
go version
if [ $? -ne 0 ]; then
    echo "❌ Go 安装失败，请检查日志。"
    exit 1
fi

# =====================
# 下载依赖模块
# =====================
echo "开始下载依赖模块..."
for dep in "${DEPENDENCIES[@]}"; do
    echo "👉 正在下载: $dep"
    go install "$dep"
done

# =====================
# 构建你的项目
# =====================
if [ ! -d "$PROJECT_DIR" ]; then
    echo "❌ 项目目录不存在: $PROJECT_DIR"
    echo "请将你的 Go 项目放在该目录下，再重新运行脚本。"
    exit 1
fi

cd "$PROJECT_DIR"
echo "开始构建项目..."
go build -o "$BINARY_PATH" main.go
if [ $? -ne 0 ]; then
    echo "❌ 构建失败，请检查代码是否正确。"
    exit 1
fi

chmod +x "$BINARY_PATH"

# =====================
# 创建 systemd 服务
# =====================
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

echo "创建 systemd 服务文件: $SERVICE_FILE"

sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=Go Monitor Server
After=network.target

[Service]
User=$SERVICE_USER
WorkingDirectory=$PROJECT_DIR
ExecStart=$BINARY_PATH
Restart=always
Environment="GOPROXY=https://goproxy.io,direct"

[Install]
WantedBy=multi-user.target
EOF

# =====================
# 启动并启用服务
# =====================
echo "加载 systemd 并启动服务..."
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable --now "$SERVICE_NAME"
sudo systemctl start "$SERVICE_NAME"

# =====================
# 检查服务状态
# =====================
echo "检查服务状态..."
sudo systemctl status "$SERVICE_NAME" --no-pager

echo "✅ 脚本执行完成！"
echo "🟢 服务已启动，可通过以下命令查看状态：systemctl status $SERVICE_NAME"